package com.example.redis.Controller;

import cn.hutool.core.util.RandomUtil;
import com.example.redis.domain.ResultVO;
import com.example.redis.domain.UserDO;
import com.example.redis.service.UserService;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/cache")
public class CacheController {

    @Autowired
    private UserService userService;

    @GetMapping("/getCache")
    public ResultVO getEacheByCacheManager(@RequestParam Integer id) {
        UserDO userDO = userService.getCache(id);
        return ResultVO.ok(userDO);
    }

    @DeleteMapping("/delCache")
    public ResultVO delEacheByMapper(@RequestParam Integer id) {
        userService.delCache(id);
        return ResultVO.ok();
    }

    @PostMapping("/updateCache")
    public ResultVO updateEacheByMapper(@RequestParam Integer id) {
        UserDO userDO = new UserDO();
        userDO.setId(id);
        userDO.setUserName("name" + RandomUtil.randomString(6));
        userDO.setAge(26);
        userDO.setPassword(RandomUtil.randomNumbers(6));
        userService.updateCache(userDO);
        return ResultVO.ok();
    }

    @GetMapping("/cacheGet")
    @ApiOperation("注解式缓存-获取")
    public UserDO cache(@RequestParam Integer id) {
        return userService.getUserById(id);
    }

    @DeleteMapping("/cacheDel")
    @ApiOperation("注解式缓存-删除")
    public void cacheDel(@RequestParam Integer id) {
        userService.deleTest(id);
    }


    @SneakyThrows
    @GetMapping("/guavaTest")
    @ApiOperation("guava")
    public void guavaTest(@RequestParam Integer id) {
        // 创建一个缓存实例
        Cache<String, String> cache = CacheBuilder.newBuilder()
                // 初始容量
                .initialCapacity(5)
                // 最大缓存数，超出淘汰
                .maximumSize(10)
                // 过期时间
                .expireAfterWrite(3, TimeUnit.SECONDS)
                .build();

        // 写入缓存数据
        cache.put("userName", "张三");

        // 读取缓存数据
        String value1 = cache.get("userName", () -> {
            // 如果key不存在，会执行回调方法
            return "key已过期";
        });
        System.out.println("第一次查询结果：" + value1);

        // 停顿4秒
        Thread.sleep(4000);

        // 读取缓存数据
        String value2 = cache.get("userName", () -> {
            // 如果key不存在，会执行回调方法
            return "key已过期";
        });
        System.out.println("第二次查询结果：" + value2);
    }


}
